<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="5" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            ref="tree"
            :data="deptOptions"
            :props="defaultProps"
            expand-on-click-node
            :filter-node-method="filterNode"
            :auto-expand-parent="false"
            :indent="30"
            icon-class="el-icon-rank"
            accordion
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="19" :xs="24">
        <el-form v-show="showSearch" ref="queryForm" :model="queryOrgParams" :inline="true" label-width="68px">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="queryOrgParams.name"
              placeholder="请输入用户名称"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleOrgQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input
              v-model="queryOrgParams.mobile"
              placeholder="请输入手机号码"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleOrgQuery"
            />
          </el-form-item>
          <el-form-item label="是否在职" prop="is_staff">
            <el-select v-model="queryOrgParams.is_staff" placeholder="用户状态" clearable size="small" style="width: 240px">
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item v-if="false" label="创建时间">
            <el-date-picker
              v-model="dateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleOrgQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetOrgQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除
            </el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
            >导入
            </el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出
            </el-button>
          </el-col>
          <!-- <right-toolbar :show-search.sync="showSearch" :columns="columns" @queryTable="getOrgUserList" /> -->
        </el-row>

        <el-table v-loading="orgLoading" :data="userOrgList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column key="id" label="用户编号" align="center" prop="id" />
          <!-- <el-table-column
            key="name"
            label="用户名称"
            align="center"
            prop="name"
            :show-overflow-tooltip="true"
          /> -->
          <el-table-column key="name" label="用户昵称" align="center" prop="name" :show-overflow-tooltip="true" />
          <el-table-column key="deptName" label="部门" align="center" prop="dept.deptName" :show-overflow-tooltip="true" />

          <el-table-column key="mobile" label="手机号码" align="center" prop="mobile" width="120" />

          <el-table-column key="is_staff" label="是否在职" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.is_staff" disabled />
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="create_datetime" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.create_datetime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="orgTotal > 0"
          :total="orgTotal"
          :page.sync="queryOrgParams.pageNum"
          :limit.sync="queryOrgParams.pageSize"
          @pagination="getOrgUserList"
        />
      </el-col>
    </el-row>
    <!-- 添加或修改参数配置对话框 -->
    <el-drawer :title="title" :visible.sync="open" size="50%" :with-header="true">
      <el-form ref="form" :model="userOrgForm" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="name">
              <el-input v-model="userOrgForm.name" placeholder="请输入客户姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <treeselect v-model="userOrgForm.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="mobile">
              <el-input v-model="userOrgForm.mobile" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userOrgForm.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="userOrgForm.gender" placeholder="请选择">
                <el-option
                  v-for="dict in sexOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否在职">
              <el-radio-group v-model="userOrgForm.is_staff">
                <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位">
              <!-- <el-select v-model="form.postIds" multiple placeholder="请选择">
                <el-option
                  v-for="item in postOptions"
                  :key="item.id"
                  :label="item.postName"
                  :value="item.id"
                  :disabled="item.status == 0"
                />
              </el-select> -->
              <el-select v-model="userOrgFormCache.posts" placeholder="岗位" multiple filterable clearable size="small">
                <el-option
                  v-for="dict in post_options"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                >{{ dict.dictLabel }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="userOrgForm.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <div style="text-align: center">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import {
  addUser,
  delUser,
  exportUser,
  getUser,
  listUser,
  updateUser
} from "@/api/company/user";
// import { treeselect } from "@/api/company/dept";
import { treeselect } from "@/api/vadmin/permission/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      orgLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      orgTotal: 0,
      // 用户表格数据
      userOrgList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // // 默认密码
      // initPassword: undefined,
      // 日期范围
      // dateRange: [],
      // 状态数据字典
      statusOptions: [
        { dictLabel: "在职", dictValue: true },
        { dictLabel: "离职", dictValue: false }
      ],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      post_options: [],
      // 表单参数
      userOrgForm: {},
      userOrgFormCache: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryOrgParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        mobile: undefined,
        is_active: undefined,
        deptId: undefined
      },
      // 表单校验
      rules: {
        name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        mobile: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getOrgUserList();
    this.getTreeselect();
    // this.getDicts("sys_normal_disable").then(response => {
    //   this.statusOptions = response.data;
    // });
    this.getDicts("sys_user_sex").then((response) => {
      this.sexOptions = response.data;
    });
    // this.getConfigKey("sys.user.initPassword").then((response) => {
    //   this.initPassword = response.msg;
    // });
    this.getDicts("post_options").then((response) => {
      this.post_options = response.data;
    });
  },
  methods: {
    /** 查询用户列表 */
    getOrgUserList() {
      this.orgLoading = true;
      listUser(this.queryOrgParams).then(
        (response) => {
          this.userOrgList = response.data.results;
          this.orgTotal = response.data.count;
          this.orgLoading = false;
        }
      );
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = this.handleTree(response.data, "id");
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryOrgParams.deptId = data.id;
      this.getOrgUserList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.userOrgForm = {
        id: undefined,
        deptId: undefined,
        name: undefined,
        password: undefined,
        mobile: undefined,
        email: undefined,
        gender: undefined,
        is_staff: true,
        remark: undefined,
        posts: undefined
        // postIds: [],
        // roleIds: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleOrgQuery() {
      this.queryOrgParams.page = 1;
      this.getOrgUserList();
    },
    /** 重置按钮操作 */
    resetOrgQuery() {
      // this.dateRange = [];
      this.queryOrgParams.deptId = "";
      this.resetForm("queryForm");
      this.handleOrgQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();
      this.open = true;
      this.title = "添加用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      const id = row.id || this.ids;
      getUser(id).then((response) => {
        this.userOrgForm = response.data;

        this.userOrgFormCache = Object.assign({}, this.userOrgForm);
        if (this.userOrgFormCache.posts) {
          this.userOrgFormCache.posts = this.userOrgFormCache.posts.split(",");
        }
        this.open = true;
        this.title = "修改用户";
        // this.form.password = "";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.userOrgForm.posts = this.userOrgFormCache.posts.length
            ? this.userOrgFormCache?.posts?.toString()
            : "";
          if (this.userOrgForm.id !== undefined) {
            updateUser(this.userOrgForm).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getOrgUserList();
            });
          } else {
            addUser(this.userOrgForm).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getOrgUserList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.id || this.ids;
      this.$confirm(
        '是否确认删除用户编号为"' + userIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delUser(userIds);
        })
        .then(() => {
          this.getOrgUserList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryOrgParams = this.queryOrgParams;
      this.$confirm("是否确认导出所有用户数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportUser(queryOrgParams);
        })
        .then((response) => {
          this.download(response.data.file_url, response.data.name);
        });
    }
  }
};
</script>
